'''
Created on 06/04/2009

@author: Edward
'''
from yarra.event.eventmanager import EventManager
import datetime
import threading


class TimerServiceListener(threading.Thread):
    '''
    classdocs
    '''

    __timer_queue = None
    __event_manager = None
    STOP_EVENT = "STOP"
    
    def __init__(self, timer_queue):
        '''
        Constructor
        '''
        self.__timer_queue = timer_queue
        self.__event_manager = EventManager()
        threading.Thread.__init__(self)
            
    def run(self):
        while True:
            (timestamp, event) = self.__timer_queue.get()
            if event != self.STOP_EVENT:
                date_time_now = datetime.datetime.now()
                time_delta = timestamp - date_time_now
                zero_microseconds = datetime.timedelta(microseconds=0)            
                if time_delta <= zero_microseconds:
                    self.__event_manager.add_event(event)
                else:
                    self.__timer_queue.put(timestamp, event)
            else:
                break
            
    def stop_listener(self):
        timestamp = datetime.datetime.now()
        self.__timer_queue.put(timestamp, self.STOP_EVENT)